# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/7/24

library(plyr)
library(gridExtra)
library(scales)
library(egg)
library(VennDiagram)
library(optparse)
library(magrittr)
library(tidyverse)

createWhenNoExist <- function(f){
    ! dir.exists(f) && dir.create(f)
}

option_list <- list(
make_option("--i", default = "AllMet.csv", type = "character", help = "metabolite data file"),
make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file"),
make_option("--config", default = "config.csv", type = "character", help = "config file")
)
opt <- parse_args(OptionParser(option_list = option_list))

configData <- read.csv(opt$config, header = F, stringsAsFactors = F) %>%
    set_colnames(c("arg", "value")) %>%
    column_to_rownames("arg")

configData

pValue <- configData["diffMethod.pValue", "value"] %>%
as.numeric()
fdr <- configData["diffMethod.fdr", "value"] %>%
as.numeric()
log2FC <- configData["diffMethod.log2FC", "value"] %>%
as.numeric()

parent <- "./"
createWhenNoExist(parent)

finalDf <- read_csv("AllMet_Test.csv") %>%
    rowwise() %>%
    do({
        result <- as.data.frame(.)
        p <- result[1, "P"]
        logFc <- result[1, "log2FC"]
        q <- result[1, "FDR"]
        value <- if (p < pValue & q <= fdr & abs(logFc) >= log2FC) {
            1
        }else 0
        result$IS_Uni_P_Sig <- value
        result
    }) %>%
    select(c("Metabolite", "IS_Uni_P_Sig")) %>%
    filter(IS_Uni_P_Sig == 1)

head(finalDf)
outFileName <- paste0(parent, "/Markers.txt")
write_tsv(finalDf, outFileName)





